package com.blog.util;

import java.sql.*;

/**
 * @ClassName DBUtil
 * @Description TODO
 * @Author zhongge
 * @Version 1.0
 */
public class DBUtil {
    //数据库路径
    private final static String URL = "jdbc:mysql://localhost:3306/blog_db";
    //数据库用户名
    private final static String USER = "root";
    //数据库密码
    private final static String PASSWORD = "123456";

    //注册驱动
    //加载这个类的时候就创建驱动
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("✅ MySQL驱动加载成功");
        } catch (ClassNotFoundException e) {
            System.err.println("❌ MySQL驱动加载失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    //获取链接==》建立和图书馆的关系
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }

    //交流方式（动态）
    //给出结果（动态）

    //关闭资源
    public static void close(Connection connection,
                             Statement statement,
                             ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

    }
    //关闭资源
    public static void close(Connection connection,
                             Statement statement) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

    }
    // 测试数据库连接
    public static void main(String[] args) {
        try (Connection conn = DBUtil.getConnection()) {
            System.out.println("✅ 数据库连接成功：" + conn);
        } catch (SQLException e) {
            System.err.println("❌ 数据库连接失败：" + e.getMessage());
        }
    }
}
